package com.edu.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.demo.anno.AutoCustomAnnotation;
import com.edu.demo.entity.UsersInfo;
import com.edu.demo.entity.dto.UserLoginDTO2;
import com.edu.demo.error.costom.PassWordException;
import com.edu.demo.error.costom.PhoneNumberAlreadyExistsException;
import com.edu.demo.error.costom.UserNameException;
import com.edu.demo.mapper.UsersInfoMapper;
import com.edu.demo.result.Result;
import com.edu.demo.service.IUsersInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author Ashe1y
 * @since 2024-03-13
 */
@Slf4j
@Service
public class UsersInfoServiceImpl extends ServiceImpl<UsersInfoMapper, UsersInfo> implements IUsersInfoService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void register(UsersInfo usersInfo) {
        //查询条件
        QueryWrapper<UsersInfo> phone = new QueryWrapper<UsersInfo>().eq("phone", usersInfo.getPhone());
        QueryWrapper<UsersInfo> username = new QueryWrapper<UsersInfo>().eq("username", usersInfo.getUsername());
        //判断手机号是否存在
        UsersInfo usersInfo1 = getOne(phone);


        if (getOne(username) != null) {
            throw new UserNameException();
        }
        if (usersInfo1 != null) {
            throw new PhoneNumberAlreadyExistsException();
        }
        //MD5加密
        //得到md5
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        //盐值 截取0-20位
        String salt = IdUtil.simpleUUID().substring(0, 20);
        //设置盐值
        md5.setSalt(salt.getBytes());
        //消化盐值 转为16进制 digest:消化 Hex:16进制
        String md5Pass = DigestUtil.md5Hex(usersInfo.getPassword());
        usersInfo.setPassword(md5Pass);
        usersInfo.setSalt(salt);

        //返回当前数据ID
        this.save(usersInfo);


        //返回影响行数
        //getBaseMapper().insert(usersInfo);
    }

    @Override
    public UserLoginDTO2 login(UsersInfo usersInfo) {
        //查询条件
        QueryWrapper<UsersInfo> queryWrapper = new QueryWrapper<UsersInfo>()
                .eq("username", usersInfo.getUsername());
        UsersInfo usersInfo1 = getOne(queryWrapper);
        if(usersInfo1==null){
            throw new PassWordException();
        }
        //如果有信息查询盐值
        String salt = usersInfo1.getSalt();
        //Md5加密
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        //（设置盐值）
        md5.setSalt(salt.getBytes());
        //把userinfo拿来加密
        String md5Pass = md5.digestHex(usersInfo.getPassword());
        //判断两个加密后的密码是否一致
        if(!md5Pass.equals(usersInfo1.getPassword())){
            throw new PassWordException();
        }

        UserLoginDTO2 userLoginDTO = new UserLoginDTO2();
        //抹掉密码
        BeanUtil.copyProperties(usersInfo1,userLoginDTO);
        //信息脱敏
        userLoginDTO.setPhone(DesensitizedUtil.mobilePhone(userLoginDTO.getPhone()));
        userLoginDTO.setIdCard(DesensitizedUtil.idCardNum(userLoginDTO.getIdCard(),3,6));
        return userLoginDTO;
    }

    @Override
    public List<UserLoginDTO2> findByPhone(String phone) {
        //手机号模糊查询
        QueryWrapper<UsersInfo> queryWrapper = new QueryWrapper<UsersInfo>()
                .likeRight("phone", phone);
        List<UsersInfo> list = list(queryWrapper);
        ArrayList<UserLoginDTO2> userLoginDTO2s = new ArrayList<>();
        if (userLoginDTO2s != null) {
            for (UsersInfo usersInfo : list) {
                UserLoginDTO2 userLoginDTO2 = new UserLoginDTO2();
                BeanUtil.copyProperties(usersInfo, userLoginDTO2);
                userLoginDTO2.setPhone(DesensitizedUtil.mobilePhone(userLoginDTO2.getPhone()));
                userLoginDTO2.setIdCard(DesensitizedUtil.idCardNum(userLoginDTO2.getIdCard(), 3, 4));
                userLoginDTO2s.add(userLoginDTO2);
            }
        }
        return userLoginDTO2s;
    }

    @AutoCustomAnnotation(group = "userinfo:")
    @Override
    public UsersInfo selectById(Integer id) {
        return getById(id);
    }


}
